package com.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class TokenFilter extends ZuulFilter {
    //定义该过滤器的执行时机，pre代表在请求执行之前拦截
    @Override
    public String filterType() {
        return "pre";
    }

    //过滤器的执行顺序，定义在过滤链的的执行顺序
    @Override
    public int filterOrder() {
        return 0;
    }

    //判断过滤器是否生效
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //编写拦截器逻辑,判断是否有token值
    @Override
    public Object run() throws ZuulException {
        //获取上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String userToken = request.getParameter("userToken");
        if(StringUtils.isEmpty(userToken)){
            requestContext.setSendZuulResponse(false);//不会再继续往下执行
            requestContext.setResponseStatusCode(401);//设置返回状态码
            requestContext.setResponseBody("userToken is null");
            return null;
        }
        //正常执行调用其他服务接口
        return null;
    }
}
